package com.ttbj.websocket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class PushSalMessageHandler extends TextWebSocketHandler{
	
	public final static Logger LOGGER = LoggerFactory.getLogger(PushSalMessageHandler.class); 
	private final static List<WebSocketSession> sessions = Collections.synchronizedList(new ArrayList<WebSocketSession>());
	
	//连接建立后处理
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		sessions.add(session);
		LOGGER.info("connect to the websocket success......当前数量:{}", sessions.size());
	}
	
	//接收文本消息，并发送出去:js调用websocket.send时候，会调用该方法
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		LOGGER.info("接收到的消息：{}", message.getPayload());
		super.handleTextMessage(session, message);
	}
	
	//抛出异常时处理
	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		if (session.isOpen()) {
			session.close();
		}
		LOGGER.error("websocket chat connection closed...");
		sessions.remove(session);
	}
	
	//连接关闭后处理
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		LOGGER.info("websocket chat connection closed");
		String userName = (String) session.getAttributes().get("WEBSOCKET_USERNAME");
		LOGGER.info("用户：{}退出", userName);
		sessions.remove(session);
		LOGGER.info("剩余在线用户：{}", sessions.size());
	}

	@Override
	public boolean supportsPartialMessages() {
		return super.supportsPartialMessages();
	}
	
	//给某个用户发送消息
	public void sendMessageToUser(String userName, TextMessage textMessage) {
		for (WebSocketSession webSocketSession : sessions) {
			if (webSocketSession.getAttributes().get("WEBSOCKET_USERNAME").equals(userName)) {
				try {
					if (webSocketSession.isOpen()) {
						webSocketSession.sendMessage(textMessage);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;
			}
		}
	}
	
	//给所有在线用户发送消息
	public void sendMessageToUsers(TextMessage textMessage) {
		for (WebSocketSession webSocketSession : sessions) {
			try {
				if (webSocketSession.isOpen()) {
					webSocketSession.sendMessage(textMessage);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
